package com.blog.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog.admin.dao.AdminMapper;
import com.blog.admin.entity.Admin;
import com.blog.admin.service.LoginService;
import com.blog.admin.util.JWTUtil;
import com.blog.admin.vo.ErrorCode;
import com.blog.admin.vo.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public WebResult<JSONObject> login(JSONObject loginParam) {
        String username = loginParam.getString("username");
        String password = loginParam.getString("password");

        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername, username).eq(Admin::getPassword,password);
        Admin admin = adminMapper.selectOne(lambdaQueryWrapper);

        if (admin == null) {
            return WebResult.<JSONObject>builder()
                    .code(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode())
                    .message(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg())
                    .build();
        } else {
            HashMap<String, String> payload = new HashMap<>();
            payload.put("username",username);
            payload.put("id", admin.getId().toString());
            String token = JWTUtil.getToken(payload);
            stringRedisTemplate.opsForValue().set("TOKEN_ADMIN" + token, JSON.toJSONString(admin), 7, TimeUnit.DAYS);
            JSONObject result = new JSONObject();
            result.put("token", token);
            return WebResult.<JSONObject>builder()
                    .code(200)
                    .message(WebResult.REQUEST_STATUS_SUCCESS)
                    .data(result)
                    .build();
        }
    }

    @Override
    public WebResult<String> logout(String token) {
        Boolean delete = stringRedisTemplate.delete("TOKEN_ADMIN" + token);
        System.out.println(delete);
        return WebResult.<String>builder()
                .code(200)
                .message(WebResult.REQUEST_STATUS_SUCCESS)
                .data(null)
                .build();
    }

}
